import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import type { UserState } from './types'
import type { PermissionType } from '@/services/types'

const name = import.meta.env.VITE_STORE_NAME
export const useUserStore = defineStore(`${name}-user`, {
  state: (): UserState => ({
    token: '',
    userInfo: { userName: 'viteAdmin' },
    permissions: [
      {
        functionCode: 'assets',
        functionName: '',
      },
      {
        functionCode: 'catalog',
        functionName: '',
      },
      {
        functionCode: 'dir',
        functionName: '',
      },
      {
        functionCode: 'quality',
        functionName: '',
      },
      {
        functionCode: 'rule',
        functionName: '',
      },
      {
        functionCode: 'task',
        functionName: '',
      },
      {
        functionCode: 'meta',
        functionName: '',
      },
      {
        functionCode: 'analysis',
        functionName: '',
      },
      {
        functionCode: 'manage',
        functionName: '',
      },
      {
        functionCode: 'catalog-create',
        functionName: '',
      },
    ],
    userMenus: [],
    userTabs: [],
  }),
  getters: {},
  actions: {
    // Set Token
    setToken(token: string) {
      this.token = token
    },
    // Set setUserInfo
    setUserInfo(userInfo: UserState['userInfo']) {
      this.userInfo = userInfo
    },
    setPermissions(list: PermissionType[]) {
      this.permissions = list
    },
    setUserMenu(routes: RouteRecordRaw[]) {
      this.userMenus = (routes[0]?.children || []) as any[]
    },
    setUserTabs(tabs: any[]) {
      this.userTabs = tabs
    },
    async logout() {
      // 清除缓存的用户信息
      this.setUserInfo({
        userName: '',
      })
      this.setPermissions([])
      // 清除缓存的token
      this.setToken('')
    },
  },
  persist: true,
})
